<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\TempVerificationCode;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rules;
use Illuminate\Support\Facades\Auth;
use Illuminate\Auth\Events\Registered;
use App\Providers\RouteServiceProvider;

class RegisteredUserController extends Controller
{
    /**
     * Display the registration view.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
        return view('auth.register');
    }

    /**
     * Handle an incoming registration request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request)
    {
        Log::info('开始处理注册请求', $request->all());

        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:'.User::class],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
            'code' => ['required', 'digits:6']
        ]);

        Log::info('验证通过，开始检查验证码');

        // 验证码最终检查
        $verificationCode = TempVerificationCode::where('email', $request->email)
            ->where('code', $request->code)
            ->where('type', 'register')
            ->first();

        if (!$verificationCode || $verificationCode->expired_at < now()) {
            Log::warning('验证码检查失败', [
                'email' => $request->email,
                'code' => $request->code,
                'verification_exists' => (bool)$verificationCode,
                'expired' => $verificationCode ? $verificationCode->expired_at < now() : null
            ]);
            return back()->withErrors(['code' => '验证码无效或已过期']);
        }

        Log::info('验证码检查通过，开始创建用户');

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        Log::info('用户创建成功，开始清理验证码');

        try {
            // 记录删除前的验证码数量
            $beforeCount = TempVerificationCode::where('email', $request->email)
                ->where('type', 'register')
                ->count();

            // 删除所有与该邮箱相关的验证码记录
            $deleted = TempVerificationCode::where('email', $request->email)
                ->where('type', 'register')
                ->delete();

            // 记录删除后的验证码数量
            $afterCount = TempVerificationCode::where('email', $request->email)
                ->where('type', 'register')
                ->count();

            Log::info('验证码删除操作完成', [
                'email' => $request->email,
                'before_count' => $beforeCount,
                'deleted_count' => $deleted,
                'after_count' => $afterCount
            ]);

        } catch (\Exception $e) {
            Log::error('删除验证码失败', [
                'email' => $request->email,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
        }

        event(new Registered($user));

        Auth::login($user);

        Log::info('注册流程完成，准备跳转');

        return redirect(RouteServiceProvider::HOME);
    }
} 